$ = (selector) => {
  return document.querySelector(selector)
}

// 判断页面是否加载完成
function isLoad(tabs) {
  let tabStatus = tabs.length ? tabs[0].status : null;
  if (tabStatus != 'complete') {
    alert('等待页面加载完成');
    return false;
  } else {
    return true
  }
}

// 存储数据
async function setStorage(key, value) {
  return await new Promise((resolve, reject) => {
    chrome.storage.local.set({ [key]: value }, function () {
      console.log('Value is set to' + value);
      if (Boolean(value)) {
        resolve(value)
      } else {
        reject(null)
      }
    });
  })
}

// 获取存储数据
async function getStorage(key) {
  try {
    return await new Promise((resolve, reject) => {
      chrome.storage.local.get([key], function (result) {
        console.log('Value currently is' + result[key]);
        let val = result[key]
        if (Boolean(val)) {
          resolve(val)
        } else {
          reject(val)
        }
      });
    })
  } catch (e) { }
}

const is188bifen = (url) => {
  return /^https?:\/\/www\.188bifen\.com\/.*$/.test(url)
}

window.onload = async () => {
  chrome.tabs.query({ active: true, currentWindow: true }, async function (tabs) {
    let tabId = tabs.length ? tabs[0].id : null;
    // alert(JSON.stringify(tabs))
    let tabUrl = tabs.length ? tabs[0].url : null;
    // 判断网址是否为 www.188bifen.com 显示隐藏 插件页面
    if(is188bifen(tabUrl) == false) {
      $('body').style.display = 'none'
    }else{
      $('body').style.display = 'block'
    }
    // 控制当前页面DOM
    chrome.scripting.executeScript({
      target: { tabId },
      // args: [],
      function: () => {
        console.log('插件 进入前台')
      }
    });
  });
}


// 开始执行
$('#start').onclick = async (event) => {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    let tabId = tabs.length ? tabs[0].id : null;
    if (!isLoad(tabs)) return;
    // alert(JSON.stringify(tabs))
    chrome.scripting.executeScript({
      target: { tabId },
      args: [],
      function: () => {
        console.log('开始执行')
      }
    });
  });
}

// 停止执行
$('#stop').onclick = async (event) => {
  // chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  //   let tabId = tabs.length ? tabs[0].id : null;
  //   if (!isLoad(tabs)) return;
  //   // alert(JSON.stringify(tabs))
  //   chrome.scripting.executeScript({
  //     target: { tabId },
  //     args: [],
  //     function: () => {
  //       console.log('停止执行')
  //     }
  //   });
  // });
}

